const fs = require('fs');
const path = require('path');
const EventEmitter = require('events');
const resolve = (filename) => {
  return path.resolve(__dirname, filename);
};

/*
在window下 换行回车(准确来说是回车换行)是\r\n 0x0d 0x0a ASCII
在mac下 只是\n 0x0a
*/
class LineReader extends EventEmitter {
  constructor(path) {
    super();
    this.RETURN = 0x0d; //13
    this.LINE = 0x0a; //10
    this._rs = fs.createReadStream(path);
    this.arr = [];
    this.on('newListener', (eventName) => {
      if (eventName === 'line') {
        this._rs.on('readable', () => {
          let bf; //读出来的是 <Buffer 31> 这样的，即使只读一个，so要拿到那一个字节的话需要char[0]
          while (bf = this._rs.read(1)) {
            const char = bf[0];
            switch (char) {
              // windows↓当碰到\r时 表示这一行ok了
              case this.RETURN:
                this.emit('line', Buffer.from(this.arr).toString());
                this.arr.length = 0;
                const next = this._rs.read(1);
                console.log('next:',next);
                if (next && next[0] !== this.LINE) this.arr.push(next[0]);
                break;
              //mac↓
              case this.LINE:
                this.emit('line', Buffer.from(this.arr).toString());
                this.arr.length = 0;
                break;
              default:
                this.arr.push(char);
            }
          }
        });

        this._rs.on('end', () => {
          //防止最后一行没有换行回车 导致最后一行的内容没有发射出去
          // console.log(1);
          if (this.arr.length !== 0) {
            // console.log(2);
            this.emit('line', Buffer.from(this.arr).toString());
          }
        });
      }
    });
  }
}

let lineReader = new LineReader(resolve('1.txt'));
lineReader.on('line', function (data) {
  console.log(data);
});
